package com.itheima.goods.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.goods.pojo.Spec;
import com.itheima.goods.service.SpecService;
import entity.PageResult;
import entity.Result;
import entity.StatusCode;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/spec")
@CrossOrigin
public class SpecController {
    @Autowired
    SpecService specService;

    @GetMapping()
    public Result findAll() {
        List<Spec> specs = specService.findAll();
        return new Result(true, StatusCode.OK, "查询成功", specs);
    }

    @PostMapping()
    public Result add(@RequestBody Spec spec) {
        specService.save(spec);
        return new Result(true, StatusCode.OK, "添加成功");
    }

    @GetMapping("search/{page}/{size}")
    public Result findPage(@PathVariable("page") Integer page,
                           @PathVariable("size") Integer size) {
        Page<Spec> pages = specService.page(new Page<Spec>(page, size));
        PageResult<Spec> specPageResult = new PageResult<>();
        specPageResult.setTotal(pages.getTotal());
        specPageResult.setRows(pages.getRecords());
        return new Result(true, StatusCode.OK, "查询成功", specPageResult);
    }

    @PostMapping("search/{page}/{size}")
    public Result findPage(@PathVariable("page") Integer page,
                           @PathVariable("size") Integer size,
                           @RequestBody Map searchMap) {

        PageResult pageResult= specService.findPage(page, size, searchMap);

        return new Result(true, StatusCode.OK, "查询成功", pageResult);
    }

    @GetMapping("/{id}")
    public Result findById(@PathVariable("id") Integer id) {
        Spec spec = specService.getById(id);
        return new Result(true, StatusCode.OK, "查询成功", spec);
    }

    @PutMapping("/{id}")
    public Result update(@RequestBody Spec spec,
                         @PathVariable("id") Integer id) {
        LambdaQueryWrapper<Spec> wrapper = Wrappers.<Spec>lambdaQuery();
        wrapper.eq(Spec::getId, id);
        specService.update(spec, wrapper);
        return new Result(true, StatusCode.OK, "修改成功");
    }

    @DeleteMapping("/{id}")
    public Result delete(@PathVariable("id") Integer id) {
        specService.removeById(id);
        return new Result(true, StatusCode.OK, "删除成功");
    }
}
